package com.example.online_retailers.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.online_retailers.dto.Result;
import com.example.online_retailers.entity.Wallet;
import com.example.online_retailers.service.TradeInfoService;
import com.example.online_retailers.service.WalletService;
import com.example.online_retailers.mapper.WalletMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
* @author 欣欣
* @description 针对表【wallet】的数据库操作Service实现
* @createDate 2023-03-20 16:21:24
*/
@Service
public class WalletServiceImpl extends ServiceImpl<WalletMapper, Wallet>
    implements WalletService{
    @Resource
    private TradeInfoService tradeInfoService;
    @Override
    @Transactional
    public Result userPayMoney(Integer userId, BigDecimal money) {
        // 1.余额充足，则扣减余额
        boolean isSuccess = update().setSql("balance = balance - " + money)
                //where voucher_id = voucherId
                .eq("user_id", userId)
                //balance > money 使用乐观锁防止并发下出现余额不足仍然扣减余额的问题
                .ge("balance",money)
                .update();
        // 2.扣减成功，更新支出金额
        if (isSuccess) {
            tradeInfoService.update().setSql("pay_money = pay_money + " + money)
                    //where voucher_id = voucherId
                    .eq("user_id", userId)
                    .update();
            return Result.ok();
        }
        return Result.fail("消费失败");
    }

    @Override
    @Transactional
    public Result userIncomeMoney(Integer userId, BigDecimal money) {
        // 1.增加余额
        boolean isSuccess = update().setSql("balance = balance + " + money)
                //where voucher_id = voucherId
                .eq("user_id", userId)
                .update();
        // 2.更新支出金额
        boolean isSuccess1 = tradeInfoService.update().setSql("income_money = income_money + " + money)
                //where voucher_id = voucherId
                .eq("user_id", userId)
                .update();
        if (isSuccess && isSuccess1) {
            return Result.ok();
        }
        return Result.fail("退款失败");
    }
}




